<script setup>
import { ref, onMounted, nextTick } from 'vue'
import html2canvas from 'html2canvas'

// 获取图片容器的引用
const imageContainer = ref(null)
const canvas = ref(null)
const ctx = ref(null)
const isDrawing = ref(false)
const startX = ref(0)
const startY = ref(0)
const annotations = ref([]) // 存储所有标注
const isAddingText = ref(false)
const currentText = ref('')

// 初始化canvas
const initCanvas = () => {
  if (canvas.value && imageContainer.value) {
    canvas.value.width = imageContainer.value.clientWidth
    canvas.value.height = imageContainer.value.clientHeight
    ctx.value = canvas.value.getContext('2d')
    ctx.value.strokeStyle = 'red'
    ctx.value.lineWidth = 2
    ctx.value.font = '16px Arial'
  }
}

// 在组件挂载时初始化
onMounted(() => {
  initCanvas()
  // 监听窗口大小变化
  window.addEventListener('resize', initCanvas)
})

// 开始绘制
const startDrawing = (e) => {
  if (!isAnnotationMode.value || isAddingText.value) return
  
  isDrawing.value = true
  const rect = canvas.value.getBoundingClientRect()
  startX.value = e.clientX - rect.left
  startY.value = e.clientY - rect.top
}

// 绘制过程
const draw = (e) => {
  if (!isDrawing.value || !isAnnotationMode.value) return
  
  const rect = canvas.value.getBoundingClientRect()
  const currentX = e.clientX - rect.left
  const currentY = e.clientY - rect.top
  
  clearCanvas()
  redrawAnnotations()
  
  ctx.value.beginPath()
  ctx.value.strokeStyle = 'red'
  ctx.value.lineWidth = 2
  ctx.value.rect(
    startX.value,
    startY.value,
    currentX - startX.value,
    currentY - startY.value
  )
  ctx.value.stroke()
}

// 结束绘制
const stopDrawing = (e) => {
  if (isDrawing.value) {
    const rect = canvas.value.getBoundingClientRect()
    const endX = e.clientX - rect.left
    const endY = e.clientY - rect.top
    
    // 保存标注
    annotations.value.push({
      type: 'rectangle',
      x: startX.value,
      y: startY.value,
      width: endX - startX.value,
      height: endY - startY.value
    })
    
    isDrawing.value = false
    // 开始添加文字
    isAddingText.value = true
    // 将输入框定位到框的右下角
    currentText.value = ''
  }
}

// 添加文字
const addText = (e) => {
  if (e.key === 'Enter' && currentText.value.trim()) {
    const lastRect = annotations.value[annotations.value.length - 1]
    annotations.value.push({
      type: 'text',
      x: lastRect.x + lastRect.width,
      y: lastRect.y + lastRect.height,
      text: currentText.value
    })
    
    isAddingText.value = false
    currentText.value = ''
    redrawAnnotations()
  }
}

// 清除画布
const clearCanvas = () => {
  if (ctx.value && canvas.value) {
    ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height)
  }
}

// 重绘所有标注
const redrawAnnotations = () => {
  if (!ctx.value) return
  
  clearCanvas()
  annotations.value.forEach(annotation => {
    if (annotation.type === 'rectangle') {
      ctx.value.beginPath()
      ctx.value.strokeStyle = 'red'
      ctx.value.lineWidth = 2
      ctx.value.rect(
        annotation.x,
        annotation.y,
        annotation.width,
        annotation.height
      )
      ctx.value.stroke()
    } else if (annotation.type === 'text') {
      ctx.value.fillStyle = 'red'
      ctx.value.font = '16px Arial'
      ctx.value.fillText(annotation.text, annotation.x, annotation.y)
    }
  })
}

// 清除所有标注
const clearBiaoZhu = () => {
  annotations.value = []
  if (ctx.value) {
    clearCanvas()
  }
  isAddingText.value = false
  currentText.value = ''
}

// 标注模式开关
const isAnnotationMode = ref(false)

// 标注按钮点击
const onClickBiaoZhu = () => {
  isAnnotationMode.value = !isAnnotationMode.value
  if (isAnnotationMode.value) {
    // 进入标注模式时初始化 canvas
    nextTick(() => {
      initCanvas()
      // 如果有之前的标注，重新绘制
      if (annotations.value.length > 0) {
        redrawAnnotations()
      }
    })
  }
}

// 截图
const onClickJieTu = async () => {
  try {
    // 获取要截图的DOM元素
    const element = imageContainer.value
    if (!element) return

    // 配置html2canvas选项
    const options = {
      useCORS: true, // 允许跨域
      allowTaint: true, // 允许跨域图片
      scale: 2, // 提高清晰度
      logging: true, // 启用日志，方便调试
      backgroundColor: null // 保持背景透明
    }

    // 使用html2canvas进行截图
    const canvas = await html2canvas(element, options)
    
    // 将canvas转换为图片URL，设置更好的质量
    const imgUrl = canvas.toDataURL('image/png', 1.0)
    
    // 创建一个临时链接来下载图片
    const link = document.createElement('a')
    link.download = '截图.png'
    link.href = imgUrl
    document.body.appendChild(link) // 添加到文档中
    link.click()
    document.body.removeChild(link) // 清理DOM
  } catch (error) {
    console.error('截图失败:', error)
  }
}
</script>

<template>
  <div class="image-container" ref="imageContainer">
    <img 
      src="@/assets/image/环境变量图片/TJN变量path.jpg" 
      alt="" 
      crossorigin="anonymous"
      @load="() => console.log('图片加载完成')"
    >
    <canvas
      v-show="isAnnotationMode"
      ref="canvas"
      class="annotation-canvas"
      @mousedown="startDrawing"
      @mousemove="draw"
      @mouseup="stopDrawing"
      @mouseleave="stopDrawing"
    ></canvas>
    <input
      v-if="isAddingText"
      v-model="currentText"
      class="text-input"
      placeholder="输入标注文字（回车确认）"
      @keyup.enter="addText"
    >
  </div>
  <div class="btn-container">
    <button @click="onClickJieTu">截图</button>
    <button 
      @click="onClickBiaoZhu"
      :class="{ active: isAnnotationMode }"
    >标注</button>
    <button @click="clearBiaoZhu">清除标注</button>
  </div>
</template>

<style scoped>
.image-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50vw;
  height: 50vh;
  background: #fff;
  position: relative;
}

img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.annotation-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  cursor: crosshair;
}

.text-input {
  position: absolute;
  padding: 4px;
  border: 1px solid #ccc;
  font-size: 14px;
}

.btn-container {
  display: flex;
}

button {
  margin-top: 20px;
  margin-right: 10px;
  padding: 5px 15px;
}

button.active {
  background-color: #4CAF50;
  color: white;
}
</style>